/**
 * 用户地址 - 管理
 */
const pathJoin = require('../common-api/data-path')
const { router, libQuery } = require('../../lib/route')
const RxfileWrite = require('rxfile-write')

libQuery((req, res, next, method) => {
  const cookies = req.cookies
  const user = cookies.user || ''
  // console.log('cookies=', cookies)
  if (!user) {
    res.renderError('没有登录')
    return
  }
  getAddress(user, dataPath => {
    const data = require(dataPath)
    if (data) {
      setTimeout(() => {
        res.send(JSON.stringify(data))
      }, 1000);
    } else {
      res.renderError('没有找到 ' + dataPath)
    }
  })
}, '/address')

module.exports = router

function getAddress(user, callback = () => { }) {
  const dataPath = getPath(user)
  RxfileWrite.exists(dataPath).then(() => {
    callback && callback(dataPath)
  }).catch(() => {
    const newPath = getPath('0')
    callback && callback(newPath)
  })
}

function getPath(user) {
  return pathJoin('address/' + user + '.js')
}